import React, {
  ReactElement,
  useState,
  useEffect,
  useRef,
  useContext
} from 'react';
import { View, ScrollView, Image } from 'react-native';

import styles from './style';
import { BANNER_WIDTH } from '../../constant';
import Button from '../../../../../../components/Button';
import { onPressBanner } from '../../actions';
import { iconPlace } from '../../../../../../constant/resource';
import { Store } from '../../reducer';

interface HeadImage {
  url: string;
  target: string;
}

export default (): ReactElement => {
  const { state } = useContext(Store);
  const { data } = state;
  const { banners = [] } = data;
  const [currentBanner, setCurrentBanner] = useState<HeadImage>(
    banners.length > 0 ? banners[0] : { target: '', url: '' }
  );
  const scroll = useRef<ScrollView>(null);

  useEffect((): (() => void) => {
    if (banners.length < 2) {
      return (): void => {};
    }

    const timer = setInterval((): void => {
      setCurrentBanner(
        (current): HeadImage => {
          let currentBannerIndex = banners.findIndex(
            (item): boolean => item.url === current.url
          );
          if (currentBannerIndex + 1 === banners.length) {
            currentBannerIndex = 0;
          } else {
            currentBannerIndex += 1;
          }
          if (scroll && scroll.current) {
            scroll.current.scrollTo({
              x: BANNER_WIDTH * currentBannerIndex,
              y: 0,
              animated: currentBannerIndex !== 0
            });
          }
          return banners[currentBannerIndex];
        }
      );
    }, 5 * 1000);
    return (): void => {
      if (timer) {
        clearInterval(timer);
      }
    };
  }, [banners]);

  if (banners.length === 0) return <View />;

  return (
    <View style={styles.container}>
      <ScrollView
        ref={scroll}
        showsHorizontalScrollIndicator={false}
        pagingEnabled
        nestedScrollEnabled
        horizontal
        style={styles.content}
        onMomentumScrollEnd={(event): void => {
          const currentBannerIndex = Math.round(
            event.nativeEvent.contentOffset.x / BANNER_WIDTH
          );
          const localBannerIndex = banners.findIndex(
            (item): boolean => item.url === currentBanner.url
          );
          if (currentBannerIndex === localBannerIndex) return;

          if (banners.length > currentBannerIndex) {
            setCurrentBanner(banners[currentBannerIndex]);
          }
        }}
      >
        {banners.map(
          (item): ReactElement => {
            if (item.url) {
              return (
                <Button
                  activity={!!item.target}
                  activeOpacity={0.9}
                  onPress={(): void => {
                    onPressBanner(item.target);
                  }}
                >
                  <Image
                    source={{ uri: item.url }}
                    style={styles.banner}
                    defaultSource={iconPlace}
                  />
                </Button>
              );
            }
            return <View style={styles.banner} />;
          }
        )}
      </ScrollView>
      {banners.length > 1 && (
        <View style={styles.pageContainer}>
          {banners.map(
            (item): ReactElement => {
              const selected = item.url === currentBanner.url;
              return (
                <View
                  style={[styles.page, selected ? styles.selectedPage : {}]}
                />
              );
            }
          )}
        </View>
      )}
    </View>
  );
};
